import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';

import { EditableProTable, ProFormInstance } from '@ant-design/pro-components';
import {
  ProForm,
  ProFormCheckbox,
  ProFormDatePicker,
  ProFormDateRangePicker,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  StepsForm,
  EditableFormInstance,
  ActionType
} from '@ant-design/pro-components';
import {
  Button,
  DatePicker,
  Form,
  Input,
  Modal,
  Radio,
  Tag,
  Select,
  InputNumber,
  message,
  Row,
  Col,
} from 'antd';
import { modalLayoutLg, modalLayoutSm } from '@/config/layout';
import { request } from 'umi';
import { PlusOutlined } from '@ant-design/icons';

type DataSourceType = {};
const defaultData: DataSourceType[] = [];

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};



const ReturnCpm = (props: any) => {
  const { value = '', onChange = (
    value: {
      key: string;
      label: string;
    }[],
  ) => { }, index = 0, ccdata = [] } = props;
  const showValue = value == '' ? [] : value.split(' ');
  return <>
    <div className='flex'>
      {
        showValue.map((e, i) => {
          return i % 2 == 0 ? <Select placeholder='字段' onChange={(str) => {
            const nv = value.split(' ');
            nv[i] = str;
            onChange(nv.join(' '));
          }}>
            {
              ccdata.map((e, i) => {
                return e.ccType == 'Double' && i != index ? <Option key={i} value={e.ccName}>{e.ccName}</Option> : ''
              })
            }
          </Select> : <Select placeholder='计算' onChange={(str) => {
            const nv = value.split(' ');
            nv[i] = str;
            onChange(nv.join(' '));
          }}>
            <Option value='+'>加</Option>
            <Option value='-'>减</Option>
            <Option value='*'>乘</Option>
            <Option value='/'>除</Option>
          </Select>
        })
      }
      <PlusOutlined onClick={() => {
        const nv = value == '' ? (value + '\' ' + '+ \'') : (value + ' +' + ' \'');
        onChange(nv);
      }} />

    </div>
  </>
}
const DictModal = (props: any, refs: any) => {
  const [form] = Form.useForm();
  const formRef = useRef<ProFormInstance>();
  const [current, setcurrent] = useState(0)

  // const [fileList,setfileList] = useState([]);
  const [measureClassData, setmeasureClassData] = useState([]);
  const { setFieldsValue, resetFields } = form;
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [code, setCode] = useState('');
  const [pid, setpid] = useState('')
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [returnDataValue, setreturnDataValue] = useState([])
  const { TextArea } = Input;
  const editorFormRef = useRef<EditableFormInstance<DataSourceType>>();
  const [rcdata, setrcdata] = useState([]);
  const [ccdata, setccdata] = useState([]);
  const ccactionRef = useRef<ActionType>();
  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
  };

  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setCode('');
    setpid('');
    resetFields();
    setcurrent(0)
    props.callback && props.callback();
  };
  //确定
  const saveApi = () => {
    return new Promise((resolve) => {
      let Obj = formRef.current?.getFieldsValue()
      Obj = {
        ...Obj,
      };
      const url = code ? '/api/dataEncyclopedia/apis/update' : '/api/dataEncyclopedia/apis/create';
      if (code) {
        Obj.id = code;
      }

      return request(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        data: Obj,
      }).then((res) => {
        message.success(code ? '更新api成功' : '新增api成功');
        if (code) {
          resolve(true);
        } else {
          setCode(res?.data);
          setTimeout(() => {
            resolve(true);
          }, 100);
        }

      });

    });

  };

  const getDetail = (id: any) => {
    request('/api/dataEncyclopedia/apis/getInfo', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {
        id: id || code,
      },
    }).then((res) => {
      // setFieldsValue(res?.data);
      showModal();

      setTimeout(() => {
        formRef.current?.setFieldsValue(res?.data)
      }, 100);

    });
  };
  const getRc = (id: any) => {
    request('/api/dataEncyclopedia/apiRc/list', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: { "apiId": id, "pageNum": 1, "pageSize": 10000 },
    }).then((res) => {
      // setFieldsValue(res?.data);


      setTimeout(() => {
        setrcdata(res?.data?.list || [])
      }, 100);

    });
  };
  const getcc = (id: any) => {
    request('/api/dataEncyclopedia/apiCc/list', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: { "apiId": id, "pageNum": 1, "pageSize": 10000 },
    }).then((res) => {
      // setFieldsValue(res?.data);


      setTimeout(() => {
        setccdata(res?.data?.list || [])
      }, 100);

    });
  };
  const updateRc = (row) => {
    let item = { ...row, ...{} };
    let url = row.id.indexOf('new') == -1 ? '/api/dataEncyclopedia/apiRc/update' : '/api/dataEncyclopedia/apiRc/create';
    if (row.id.indexOf('new') != -1) {
      delete item['id'];
      item['apiId'] = code;
    }
    request(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: item,
    }).then((res) => {
      getRc(code);
    });



  }
  const deleteRc = (id: any) => {
    if (id.indexOf('new') != -1) {

    } else {
      request('/api/dataEncyclopedia/apiRc/delete/' + id, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
        data: {},
      }).then((res) => {
        getRc(code);
      });

    }



  }
  const deleteCc = (id: any) => {
    if (id.indexOf('new') != -1) {

    } else {
      request('/api/dataEncyclopedia/apiCc/delete/' + id, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
        data: {},
      }).then((res) => {
        getcc(code);
      });

    }



  }

  const updateCc = (row) => {
    let item = { ...row, ...{} };
    let url = row.id.indexOf('new') == -1 ? '/api/dataEncyclopedia/apiCc/update' : '/api/dataEncyclopedia/apiCc/create';
    if (row.id.indexOf('new') != -1) {
      delete item['id'];
      item['apiId'] = code;
    }

    let ccMethod = item.ccMethod;
    let ccMethodArr = ccMethod == '' ? [] : ccMethod.split(' ');
    let blName = [];
    ccMethodArr.map((e, i) => {
      if (i % 2 == 0) {
        blName.push(e);
      }
    })
    item['blName'] = blName;
    request(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: item,
    }).then((res) => {
      getcc(code);
    });
    // request('/api/dataEncyclopedia/apiCc/check', {
    //   method: 'POST',
    //   headers: {
    //     'Content-Type': 'application/json',
    //   },
    //   data: item,
    // }).then((res) => {



    // });


  }
  useImperativeHandle(refs, () => ({
    init: (id: any, qpid: any) => {
      setpid(qpid);
      if (id) {

        setCode(id);
        getDetail(id);
      } else {
        resetFields();
        showModal();
      }

      // setfileList([]);
    },
  }));
  const columns1 = [{
    title: '参数名称',
    dataIndex: 'rcName',
  }, {
    title: '参数类型',
    dataIndex: 'rcType',
    valueEnum: {
      'Double': 'Double',
      'VARCHAR': 'VARCHAR',
    },
    valueType: 'select',
  }, {
    title: '默认值',
    dataIndex: 'defaultValue',
  }, {
    title: '操作',
    valueType: 'option',
    width: 130,
    render(text, record, index, action) {
      return [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <a
          key="editable"
          onClick={() => {
            deleteRc(record.id);
          }}
        >
          删除
        </a>
      ]
    },
  },];

  const columns2 = [
    {
      title: '参数',
      dataIndex: 'ccName',
      width: 120
    },
    {
      title: '参数类型',
      dataIndex: 'ccType',
      valueEnum: {
        'Double': 'Double',
        'VARCHAR': 'VARCHAR',
      },
      valueType: 'select',
    },
    {
      title: '内容',
      dataIndex: 'ccMethod',
      renderFormItem: (record, { isEditable }) => {

        let index = record.index;
        let item = ccdata[index];
        return <>
          {
            item.ccType == 'Double' ? (isEditable ? <ReturnCpm ccdata={ccdata} index={index} value={item.ccMethod} onChange={(value) => {
              let dataSourcen = ccdata.concat([]);
              dataSourcen[index]['ccMethod'] = value;
              setccdata(dataSourcen)
            }} /> : <>{JSON.stringify(item.content)}</>) : <Input value={item.ccMethod} onChange={(e) => {
              let dataSourcen = ccdata.concat([]);
              dataSourcen[index]['ccMethod'] = e.target.value;
              setccdata(dataSourcen)
            }} />
          }
        </>
      },

    },
    {
      title: '操作',
      valueType: 'option',
      width: 130,
      render: (text, record, index, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);


          }}
        >
          编辑
        </a>,
        <a
          key="editable"
          onClick={() => {
            deleteCc(record.id);
          }}
        >
          删除
        </a>,
        // <a
        //   key="delete"
        //   onClick={() => {
        //     const tableDataSource = formRef.current?.getFieldValue('table') as DataSourceType[];
        //     formRef.current?.setFieldsValue({
        //       table: tableDataSource.filter((item) => item.id !== record.id),
        //     });
        //   }}
        // >
        //   删除
        // </a>,
      ],
    },
  ];
  useEffect(() => {
    switch (current) {
      case 0:
        if (isModalVisible) {
          getDetail(code);
        }
        break;
      case 1:
        getRc(code);
        break;
      case 2:
        getcc(code);
        break;
      default:
        break;
    }
  }, [current])
  const getFooter = () => {
    let dom = [];
    switch (current) {
      case 0:
        dom = [
          <Button type="primary" onClick={() => {
            console.log(formRef?.current?.submit())
          }}>下一步</Button>
        ]
        break;
      case 1:
        dom = [
          <Button onClick={() => {
            setcurrent(0)
          }}>上一步</Button>,
          <Button type="primary" onClick={() => {
            console.log(formRef?.current?.submit())
          }}>下一步</Button>
        ]
        break;
      case 2:
        dom = [
          <Button onClick={() => {
            setcurrent(1)
          }}>上一步</Button>,
          <Button onClick={handleCancel}>关闭</Button>
        ]
        break;
      default:
        break;
    }
    return dom;
  }
  const renderFooter = () => {
    return null;
  }
  return (
    <Modal
      title="分步表单"
      width={1200}
      onCancel={handleCancel}
      open={isModalVisible}
      destroyOnClose
      footer={getFooter()}
      bodyStyle={{
        maxHeight: window.innerHeight - 150
      }}
    >
      <StepsForm<{
        name: string;
      }>
        formRef={formRef}
        current={current}
        formProps={{
          validateMessages: {
            required: '此项为必填项',
          },
        }}
        stepsProps={{
          renderFooter: () => renderFooter(current),
        }}
        onCurrentChange={(cur) => {
          console.log(cur);
          setEditableRowKeys([]);
          setcurrent(cur)
        }}
      >
        <StepsForm.StepForm<{
          name: string;
        }>
          name="base"
          title="API基础信息"
          onFinish={async () => {
            console.log();
            await saveApi();
            return true;
          }}
        >
          <ProFormText
            name="apiName"
            label="API名称"
            placeholder="请输入API名称"
            rules={[{ required: true, message: '请输入API名称' }]}
          />
          <ProFormSelect
            label="API请求方式"
            name="apiType"
            rules={[
              {
                required: true,
              },
            ]}
            initialValue="GET"
            options={[
              {
                value: 'GET',
                label: 'GET',
              },
              { value: 'POST', label: 'POST' },
              { value: 'DELETE', label: 'DELETE' },
              { value: 'PUT', label: 'PUT' },
            ]}
          />
          <ProFormText
            name="apiUrl"
            label="API地址"
            placeholder="请输入API地址"
            rules={[{ required: true, message: '请输入API地址' }]}
          />
          {/* <Button onClick={() => {
            formRef.current?.setFieldsValue({
              apiUrl: '修改了'
            })
          }}>修改</Button> */}
        </StepsForm.StepForm>
        <StepsForm.StepForm<{
          name: string;
        }>
          name="rc"
          title="入参管理"
          onFinish={async () => {
            console.log(rcdata);
            return true;
          }}
        >
          <span style={{ display: 'none' }}>{JSON.stringify(rcdata)}</span>
          <EditableProTable<DataSourceType>
            rowKey="id"
            columns={columns1}
            value={rcdata}
            scroll={{
              y: window.innerHeight - 500
            }}
            recordCreatorProps={
              {
                position: 'bottom',
                record: () => ({ id: 'new' + (Math.random() * 1000000).toFixed(0) }),
              }
            }
            onChange={(value) => {
              let newrcdata = rcdata.concat(value);
              const uniqueArray = Object.values(newrcdata.reduce((acc, obj) => {
                acc[obj.id] = obj;
                return acc;
              }, {}));
              setrcdata(uniqueArray);
            }}
            editable={{
              type: 'single',
              editableKeys,
              onChange: setEditableRowKeys,
              onSave: (key, row) => {
                console.log(row);
                updateRc(row);
              },
              onDelete: (key, row) => {
                console.log(row);
                deleteRc(row.id);
              },
            }}
          />
        </StepsForm.StepForm>
        <StepsForm.StepForm<{
          name: string;
        }>
          name="cc"
          title="出参管理"
          onFinish={async () => {
            console.log(rcdata);
            await waitTime(2000);
            return true;
          }}
        >
          <span style={{ display: 'none' }}>{JSON.stringify(ccdata)}</span>

          <EditableProTable<DataSourceType>
            rowKey="id"
            columns={columns2}
            value={ccdata}
            actionRef={ccactionRef}
            recordCreatorProps={false}
            scroll={{
              y: window.innerHeight - 500
            }}
            onChange={(value) => {
              let newccdata = ccdata.concat(value);
              const uniqueArray = Object.values(newccdata.reduce((acc, obj) => {
                acc[obj.id] = obj;
                return acc;
              }, {}));
              setccdata(uniqueArray);
            }}
            editable={{
              type: 'single',
              editableKeys,
              onChange: setEditableRowKeys,
              onSave: (key, row) => {
                console.log(key, row);
                const targetData = ccdata.find(item => item.id === key);
                updateCc(targetData)
              },
              onValuesChange: (record, recordList) => {
                setccdata(recordList);
              },
            }}
          />
          <Button
            type="dashed" block
            onClick={() => {
              let id = 'new' + (Math.random() * 1000000).toFixed(0);
              let newccdata = ccdata.concat({
                id: id,
                ccMethod: '',
                ccName: '',
                ccType: '',
                content: '',
              });
              setccdata(newccdata);
              setEditableRowKeys([id])
            }}
            icon={<PlusOutlined />}
          >
            添加一行数据
          </Button>
        </StepsForm.StepForm>

      </StepsForm>
    </Modal>

  );
};
const AddMCom = forwardRef(DictModal);

export default AddMCom;
